﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewType : Form
    {
        public fmNewType()
        {
            InitializeComponent();
        }

        private void fmNewType_Load(object sender, EventArgs e)
        {
            //初始化
            DataTable dtRangeType = new DataTable();
            dtRangeType.Columns.Add("VALUE", typeof(int));
            dtRangeType.Columns.Add("TEXT", typeof(string));
            dtRangeType.Rows.Add(new object[] { 0, "全局" });
            dtRangeType.Rows.Add(new object[] { 1, "企业" });

            this.cbxRangeType.ValueMember = "VALUE";
            this.cbxRangeType.DisplayMember = "TEXT";
            this.cbxRangeType.DataSource = dtRangeType;
            this.cbxRangeType.SelectedIndex = 0;

            //初始化
            //分布式光伏：01、用户侧储能：13、充换电设施：100、工商业负荷：101、空调负荷：106、自备电厂：102、分布式风电：103、柴油发动机：104、其他：105
            DataTable dtResourceType = new DataTable();
            dtResourceType.Columns.Add("VALUE", typeof(string));
            dtResourceType.Columns.Add("TEXT", typeof(string));
            dtResourceType.Rows.Add(new object[] { "", "" });
            dtResourceType.Rows.Add(new object[] { "01", "分布式光伏" });
            dtResourceType.Rows.Add(new object[] { "13", "用户侧储能" });
            dtResourceType.Rows.Add(new object[] { "100", "充换电设施" });
            dtResourceType.Rows.Add(new object[] { "101", "工商业负荷" });
            dtResourceType.Rows.Add(new object[] { "106", "空调负荷" });
            dtResourceType.Rows.Add(new object[] { "102", "自备电厂" });
            dtResourceType.Rows.Add(new object[] { "103", "分布式风电" });
            dtResourceType.Rows.Add(new object[] { "104", "柴油发动机" });
            dtResourceType.Rows.Add(new object[] { "105", "其他" });


            this.cbxResourceType.ValueMember = "VALUE";
            this.cbxResourceType.DisplayMember = "TEXT";
            this.cbxResourceType.DataSource = dtResourceType;

            this.cbxResourceType.SelectedIndex = 0;

            //分布式电源（光伏,风电）:10,用户侧储能:20,充换电设施:30,其他:40
            DataTable dtGenType = new DataTable();
            dtGenType.Columns.Add("VALUE", typeof(string));
            dtGenType.Columns.Add("TEXT", typeof(string));
            dtGenType.Rows.Add(new object[] { "", "" });
            dtGenType.Rows.Add(new object[] { "10", "分布式电源（光伏,风电）" });
            dtGenType.Rows.Add(new object[] { "20", "用户侧储能" });
            dtGenType.Rows.Add(new object[] { "30", "充换电设施" });
            dtGenType.Rows.Add(new object[] { "40", "其他" });

            this.cbxGenType.ValueMember = "VALUE";
            this.cbxGenType.DisplayMember = "TEXT";
            this.cbxGenType.DataSource = dtGenType;

            this.cbxGenType.SelectedIndex = 0;

            //加载已创建公共类型
            {
                string sql = $@"SELECT id,range_type,factory_station_id,type_name,resource_type,gen_mode,gen_type FROM custom_resource_type WHERE range_type=0";
                var dt = MySQLHelper.GetDataTableBySql(MySQLHelper.targetConnectionString, sql);
                //dgType的range_type列定义为ComboBox类型键值对应按dtRangeType表对应
                if (!dgType.Columns.Contains("range_type"))
                {
                    DataGridViewComboBoxColumn rangeTypeColumn = new DataGridViewComboBoxColumn();
                    rangeTypeColumn.Name = "range_type";
                    rangeTypeColumn.DataPropertyName = "range_type";
                    rangeTypeColumn.HeaderText = "统计范围";
                    rangeTypeColumn.ValueMember = "VALUE";
                    rangeTypeColumn.DisplayMember = "TEXT";
                    rangeTypeColumn.DataSource = (cbxRangeType.DataSource as DataTable).Copy();
                    dgType.Columns.Add(rangeTypeColumn);
                }
                //dgType的gen_type列定义为ComboBox类型键值对应按dtGenType表对应
                if (!dgType.Columns.Contains("gen_type"))
                {
                    DataGridViewComboBoxColumn genTypeColumn = new DataGridViewComboBoxColumn();
                    genTypeColumn.Name = "gen_type";
                    genTypeColumn.DataPropertyName = "gen_type";
                    genTypeColumn.HeaderText = "总平台资源类型";
                    genTypeColumn.ValueMember = "VALUE";
                    genTypeColumn.DisplayMember = "TEXT";
                    genTypeColumn.DataSource = (cbxGenType.DataSource as DataTable).Copy();
                    dgType.Columns.Add(genTypeColumn);
                }

                // 设置不允许新增行
                dgType.AllowUserToAddRows = false;

                dgType.AllowUserToDeleteRows = false; // 禁止删除行

                RTypeBindingSource.DataSource = dt;

                dgType.DataSource = RTypeBindingSource;
                dgType.Columns["id"].Visible = false;
                dgType.Columns["factory_station_id"].Visible = false;
                dgType.Columns["range_type"].HeaderText = "统计范围";
                dgType.Columns["type_name"].HeaderText = "类型名称";
                dgType.Columns["resource_type"].HeaderText = "资源类型";
                dgType.Columns["gen_mode"].Visible = false;
                dgType.Columns["gen_type"].HeaderText = "总平台资源类型";
                lbTCount.Text = dt.Rows.Count.ToString();
            }
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {
            DataRow drSite = null;
            if (cbxRangeType.Text == "企业")
            {
                DataTable dtSite = SiteBindingSource.DataSource as DataTable;
                if (dtSite == null || !dtSite.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
                {
                    MessageBox.Show("选择企业请先勾选企业数据");
                    return;
                }
                drSite = dtSite.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");
            }
            if (string.IsNullOrWhiteSpace(txtTypeName.Text))
            {
                MessageBox.Show("请填写类型名称！");
                return;
            }


            //判断重名
            string sql = $@"SELECT id FROM custom_resource_type WHERE type_name={MySQLHelper.ConvertGuidToSql(txtTypeName.Text)} ";
            string factory_station_id = "";

            string strWhere = "";
            if (cbxRangeType.Text == "企业")
            {
                strWhere = $@" AND (range_type = 0 or factory_station_id={MySQLHelper.ConvertDecimalToSql(drSite["pkey"].ToString())}) ";

                factory_station_id = drSite["pkey"].ToString();
            }

            var dtt = MySQLHelper.GetDataTableBySql(MySQLHelper.targetConnectionString, sql + strWhere);
            if (dtt == null)
            {
                MessageBox.Show("同名校验出错！");
                return;
            }
            if (dtt.Rows.Count > 0)
            {
                MessageBox.Show("类型名称已存在，请修改！");
                return;
            }
            

            
            List<string> sqlList = new List<string>();
            //插入数据
            sqlList.Add($@"insert into custom_resource_type(range_type,factory_station_id,type_name,create_time,update_time,resource_type,gen_mode,gen_type)VALUES ({MySQLHelper.ConvertDecimalToSql(cbxRangeType.SelectedValue.ToString())},{MySQLHelper.ConvertGuidToSql(factory_station_id)},{MySQLHelper.ConvertGuidToSql(txtTypeName.Text)},NOW(),NOW(),{MySQLHelper.ConvertGuidToSql(cbxResourceType.Text)},{MySQLHelper.ConvertGuidToSql(cbxResourceType.SelectedValue.ToString())},{MySQLHelper.ConvertGuidToSql(cbxGenType.SelectedValue.ToString())})");
            if (await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, sqlList))
            {
                MessageBox.Show("新建分类成功");
            }
            else
            {
                MessageBox.Show("新建分类失败");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,`site_name`,pkey,parent_pkey FROM site_15min WHERE `site_name` LIKE '%{txtSiteName.Text}%'");
            if (dtA == null || dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }


            if (!dgSite.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgSite.Columns.Add(checkBoxColumn);
            }


            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;

            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            SiteBindingSource.DataSource = dtA;
            dgSite.DataSource = SiteBindingSource;

            dgSite.Columns["id"].HeaderText = "ID";
            dgSite.Columns["site_name"].HeaderText = "名称";
            dgSite.Columns["pkey"].HeaderText = "数元平台站点ID";
            dgSite.Columns["parent_pkey"].HeaderText = "数元上级节点ID";
            dgSite.AutoResizeColumns();

            dgSite.CellContentClick += dgSite_CellContentClick;
            lbCount.Text = dtA.Rows.Count.ToString();
        }

        private void dgSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgSite.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgSite.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    dgSite.EndEdit();
                    DataRowView drv = SiteBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }
                    if (drv["IsSelected"].ToString() == "True")
                    {
                        //加载已创建公共类型和选择企业类型
                        string sql = $@"SELECT id,range_type,factory_station_id,type_name,resource_type,gen_mode,gen_type FROM custom_resource_type WHERE (range_type = 0 or factory_station_id={MySQLHelper.ConvertDecimalToSql(drv["pkey"].ToString())}) order by range_type, id";
                        var dt = MySQLHelper.GetDataTableBySql(MySQLHelper.targetConnectionString, sql);

     
                        // 设置不允许新增行
                        dgType.AllowUserToAddRows = false;

                        dgType.AllowUserToDeleteRows = false; // 禁止删除行
                        RTypeBindingSource.DataSource = dt;

                        dgType.DataSource = RTypeBindingSource;
                        dgType.Columns["id"].Visible = false;
                        dgType.Columns["factory_station_id"].Visible = false;
                        dgType.Columns["range_type"].HeaderText = "统计范围";
                        dgType.Columns["type_name"].HeaderText = "类型名称";
                        dgType.Columns["resource_type"].HeaderText = "资源类型";
                        dgType.Columns["gen_mode"].Visible = false;
                        dgType.Columns["gen_type"].HeaderText = "总平台资源类型";
                        
                        lbTCount.Text = dt.Rows.Count.ToString();
                    }
                    else
                    {
                        //加载已创建公共类型
                        string sql = $@"SELECT id,range_type,factory_station_id,type_name,resource_type,gen_mode,gen_type FROM custom_resource_type WHERE range_type=0";
                        var dt = MySQLHelper.GetDataTableBySql(MySQLHelper.targetConnectionString, sql);
                        

                        // 设置不允许新增行
                        dgType.AllowUserToAddRows = false;

                        dgType.AllowUserToDeleteRows = false; // 禁止删除行

                        RTypeBindingSource.DataSource = dt;

                        dgType.DataSource = RTypeBindingSource;
                        dgType.Columns["id"].Visible = false;
                        dgType.Columns["factory_station_id"].Visible = false;
                        dgType.Columns["range_type"].HeaderText = "统计范围";
                        dgType.Columns["type_name"].HeaderText = "类型名称";
                        dgType.Columns["resource_type"].HeaderText = "资源类型";
                        dgType.Columns["gen_mode"].Visible = false;
                        dgType.Columns["gen_type"].HeaderText = "总平台资源类型";
                        lbTCount.Text = dt.Rows.Count.ToString();
                    }


                }
            }

        }

    }
}
